package com.derbysoft.ota.application.util;

import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public abstract class Calendars {

	public static Calendar of(String time) {
		return of(time, Dates.defaultDateFormat());
	}

	public static Calendar of(String time, DateFormat format) {
		return of(Dates.parse(time, format));
	}

	public static Calendar of(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		return convertToGmt(c);
	}

	public static Calendar nextDayOf(Date date) {
		Calendar cal = Calendars.of(date);
		cal.add(Calendar.DAY_OF_MONTH, 1);
		return cal;
	}


	public static TimeZone gmt0TimeZone() {
		return TimeZone.getTimeZone("GMT-0:00");
	}

	public static Date getDateOfGMT0(Calendar cal) {
		Calendar gmtCal = convertToGmt(cal);
		Calendar currentCal = Calendar.getInstance();
		int offsetFromUTC = offsetFromUTC(currentCal);
		return new Date(gmtCal.getTimeInMillis()-offsetFromUTC);
	}

	private static int offsetFromUTC(Calendar calendar) {
		Date date = calendar.getTime();
		TimeZone tz = calendar.getTimeZone();
		//Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
		long msFromEpochGmt = date.getTime();
		//gives you the current offset in ms from GMT at the current date
		return tz.getOffset(msFromEpochGmt);
	}

	public static Calendar convertToGmt(Calendar cal) {

		Date date = cal.getTime();
		int offsetFromUTC = offsetFromUTC(cal);

		//create a new calendar in GMT timezone, set to this date and add the offset
		Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
		gmtCal.setTime(date);
		gmtCal.add(Calendar.MILLISECOND, offsetFromUTC);

		return gmtCal;
	}

}
